<?php
/*
    funzioni per ottenere le informazioni del db, non presenti in posttype
    
*/

// assegna all'amministratore tutte le capability per il posttype indicato
function adleex_define_cap($singular,$plural,$extended=array()) {
	
	
	$admin = get_role('administrator');
	
	$admin->add_cap('delete_'.$plural);
	$admin->add_cap('edit_'.$plural);
	$admin->add_cap('publish_'.$plural);
	$admin->add_cap('edit_published_'.$plural);
	$admin->add_cap('delete_published_'.$plural);
	$admin->add_cap('read_private_'.$plural);
	$admin->add_cap('edit_private_'.$plural);
	$admin->add_cap('delete_private_'.$plural);
	$admin->add_cap('edit_others_'.$plural);
	$admin->add_cap('delete_others_'.$plural);
	
	foreach($extended as $cap) 
		$admin->add_cap($cap.'_'.$plural);
	
}

// ritorna una lista comma-separed dei post risultanti dalla query
function adleex_post_list($query, $pre='') {
	$result = get_posts($query);
	$list = $pre.',';
	foreach ($result as $voice) $list .= $voice->ID.':'.$voice->post_title.',';
	$list = trim($list,',');
	
	return $list;
}

// ritorna una lista comma-separed degli utenti risultanti dalla query
function adleex_user_list($query, $pre='') {
	$result = get_users($query);
	$list = $pre.',';
	foreach ($result as $voice) $list .= $voice->ID.':'.$voice->display_name.',';
	$list = trim($list,',');
	
	return $list;
	
}

function adleex_dummy_create() {

	// creo un posttype di appoggio per creare le tassonomie
	$labels = array(
			'name' => __('Dummy', ADLEEX_DOMAIN),
			'singular_name' => __('Dummy', ADLEEX_DOMAIN),
			'add_new' => __('Add', ADLEEX_DOMAIN),
			'add_new_item' => __('New', ADLEEX_DOMAIN),
			'edit_item' => __('Edit', ADLEEX_DOMAIN),
			'new_item' => __('New', ADLEEX_DOMAIN),
			'all_items' => __('All', ADLEEX_DOMAIN),
			'view_item' => __('View', ADLEEX_DOMAIN),
			'search_items' => __('search', ADLEEX_DOMAIN),
			'not_found' => __('not found', ADLEEX_DOMAIN),
			'not_found_in_trash' => __('not in trash', ADLEEX_DOMAIN),
			'parent_item_colon' => '',
			'menu_name' => __('Dummy', ADLEEX_DOMAIN)
	);


	$args = array(
			'labels' => $labels,
			'public' => false,
			'publicly_queryable' => false,
			'show_ui' => false,
			'show_in_menu' => false,
			'query_var' => false,
			'capability_type' => 'post',
			'map_meta_cap' => true,
			'supports' => array('title')
	);
	register_post_type('adleex_dummy', $args);

}



function adleex_register_taxonomy($name, $labels, $single=false, $hierarchical = true ,$cap = '', $fields = '')
{
	//$name = strtolower($labels['name']);

	$labels = array(
			'name' => __($labels['name'], ADLEEX_DOMAIN ),
			'singular_name' => __($labels['singular_name'], ADLEEX_DOMAIN ),
			'search_items' =>  __($labels['search_items'], ADLEEX_DOMAIN ),
			'all_items' => __($labels['all_items'], ADLEEX_DOMAIN ),
			'parent_item' => __($labels['parent_item'], ADLEEX_DOMAIN ),
			'parent_item_colon' => __($labels['parent_item_colon'], ADLEEX_DOMAIN ),
			'edit_item' => __($labels['edit_item'], ADLEEX_DOMAIN ),
			'update_item' => __($labels['update_item'], ADLEEX_DOMAIN ),
			'add_new_item' => __($labels['add_new_item'], ADLEEX_DOMAIN ),
			'new_item_name' => __($labels['new_item_name'], ADLEEX_DOMAIN ),
			'menu_name' => __($labels['menu_name'], ADLEEX_DOMAIN ),
	);

	if ($cap=='')
		$cap = array(
				'manage_terms' => 'manage_categories',
				'edit_terms' => 'manage_categories',
				'delete_terms' => 'manage_categories',
				'assign_terms' => 'manage_categories',
		);

	if ($single) $ui = 'radio';
	else         $ui = true;

	register_taxonomy(
	$name,
	'adleex_dummy',
	array(
	'hierarchical' => $hierarchical,
	'labels' => $labels,
	'show_ui' => $ui,
	'query_var' => true,
	'capabilities' => $cap,
	'rewrite' => array(	'slug' => $name )
	)
	);

	if ($fields!='') register_taxonomy_fields($name,$fields);

}



function wpf_set_post_meta($id,$name,$value) {
  if (!get_post_meta($id,$name)) 
        add_post_meta($id,$name,$value,true);
  else 
        update_post_meta($id,$name,$value);
}

// restituisce l'id di un post a artire dal suo nome (slug)
function wpf_post_by_name($name) {
global $wpdb;

		$q = "SELECT ID FROM $wpdb->posts WHERE post_name = '$name'";
		$val_obj = $wpdb->get_results($q,'ARRAY_A');
		$val = $val_obj[0];
		return $val['ID'];

}
// restituisce gli id che hanno come valore un custom filed con nome pari a $name e come valore uno di quelli specificati in $values
function wpf_id_by_meta($name,$values,$function = 'meta_value') {
		global $wpdb;
		$ids= array();
		foreach ($values as $val)  {
				$q = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='$name' AND $function='$val'";
				$all = $wpdb->get_results($q,'ARRAY_A');
				foreach ($all as $fasc) $ids[$fasc['post_id']]='0';
		}
		return $ids;
}
// restituisce gli id che hanno come tags almeno uno di quelli specificati in $values
function wpf_id_by_tags($values) {
		global $wpdb;
		$ids= array();
   		foreach ($values as $val)  {
 				$tag_id = $wpdb->get_var("SELECT t.term_id FROM {$wpdb->terms} t
   									JOIN {$wpdb->term_taxonomy} tt
      								ON (t.term_id = tt.term_id AND tt.taxonomy = 'media-tags')
   									WHERE t.name = '$val'");  		
				$q = "SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id='$tag_id'";
				$all = $wpdb->get_results($q,'ARRAY_A');
				foreach ($all as $fasc) $ids[$fasc['object_id']]='0';
		}
		return $ids;
}

// inserisce un termine di tassonomia, specificando anche custom field
function wpf_insert_term($term,$taxonomy,$args) {
       
       wp_insert_term($term,$taxonomy,$args);       
       unset($args['description'],$args['parent'],$args['slug']);
       $data = serialize($args);
       $name = 'field_'.$taxonomy.'_'.$term;
       if (get_option($name,'')!='') {
		update_option($name,$data);
       } else {
		add_option($name,$data,'',true);
       }
}

// ritorna il valore di un termine di tassonomia
function wpf_get_term_field_value($field,$term,$taxonomy) {
		$name = 'field_'.$taxonomy.'_'.$term;
		$args = unserialize(get_option($name));
		return $args[$field];
}
// ritorna tutti i field di una tassonomia
function wpf_get_term_fields($term,$taxonomy) {
		$name = 'field_'.$taxonomy.'_'.$term;
		$args = unserialize(get_option($name));
		return array_keys($args);
}





// restituisce la lista di progetti
function wpf_project_parent_modulo() {
global $wpdb;

		$q = "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'wpf_progetto' AND NOT post_status = 'auto-draft'";
                
		$val_obj = $wpdb->get_results($q,'ARRAY_A');
                $values = array();
		foreach($val_obj as $v) $values[$v['ID']] = $v['post_title'];
		return $values;

}


// restituisce la lista di progetti
function wpf_project_parent_scheda_spesa() {
global $wpdb;

		$q = "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status != 'auto-draft'";
		$val_obj = $wpdb->get_results($q,'ARRAY_A');		
		
		return $val_obj;

}


// restituisce la lista di moduli
function wpf_moduli_parent_scheda_attivita() {
global $wpdb;

		$q = "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'wpf_modulo' AND post_status != 'auto-draft'";
		$val_obj = $wpdb->get_results($q,'ARRAY_A');		
		
		return $val_obj;

}

// restituisce la lista di contenuti
function wpf_contenuti_parent_scheda_attivita() {
global $wpdb;

		$q = "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'wpf_contenuti' AND post_status != 'auto-draft'";
		$val_obj = $wpdb->get_results($q,'ARRAY_A');		
		
		return $val_obj;

}



// restituisce la lista di progetti
function wpf_project_parent_corso() {
global $wpdb;

		$q = "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status != 'auto-draft'";
		$val_obj = $wpdb->get_results($q,'ARRAY_A');		
		
		return $val_obj;

}

function adleex_get_query($query_name, $par1 = '', $par2 = '') {
	global $adleex_queries;

    $query = $adleex_queries[$query_name];
	
    if ($par1!=='') {
        foreach ($query as $k => $val) {
            $val = str_replace ('%1:s', $par1, $val);
            $val = str_replace ('%2:s', $par2, $val);
            $query[$k] = $val;
        }
    }
	  
    return $query;
}


// Adapted from :  http://www.bundy.ca/radio-taxonomy
// thanks to : Mitchell Bundy

if (!class_exists('wpf_Walker_Category_RadioList')):
class wpf_Walker_Category_RadioList extends Walker {
	var $tree_type = 'category';
	var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); //TODO: decouple this

	function start_lvl(&$output, $depth, $args) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent<ul class='children'>\n";
	}

	function end_lvl(&$output, $depth, $args) {
		$indent = str_repeat("\t", $depth);
		$output .= "$indent</ul>\n";
	}

	function start_el(&$output, $category, $depth, $args) {
		extract($args);
		if ( empty($taxonomy) )
			$taxonomy = 'category';

		if ( $taxonomy == 'category' )
			$name = 'post_category';
		else
			$name = 'tax_input['.$taxonomy.']';

		$class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : '';
		$output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="radio" name="'.$name.'[]" id="in-'.$taxonomy.'-' . $category->term_id . '"' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args['disabled'] ), false, false ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>';
	}

	function end_el(&$output, $category, $depth, $args) {
		$output .= "</li>\n";
	}
}
endif;

if (!class_exists("wpf_radiotax")):
class wpf_radiotax {
	
	function __construct() {
		add_action('init', array($this, 'set_taxonomies'),50);
		add_action('admin_menu', array($this, 'meta_boxes'));
	}
	
	function set_taxonomies() {
		global $wp_taxonomies;
                $all_tax = get_taxonomies(array(), 'objects');
                
		foreach ($all_tax as $tax) {
                        if ($tax->show_ui==='radio') $this->taxonomies[$tax->name]=$tax;
			$wp_taxonomies[$tax->name]->show_ui = true;
			// Default show_none to false
			if (!isset($wp_taxonomies[$tax->name]->show_none)) $wp_taxonomies[$tax->name]->show_none = false;
		}
	}
		
	function meta_box($post, $metabox) {
		do_action('radio-taxonomy_box');
		$tax = $metabox['args']['taxonomy'];?>
		<div id="taxonomy-<?php echo $tax->name ?>" class="categorydiv">
            <div class="inside">
                <div id="<?php echo $tax->name; ?>-all">
                    <ul id="<?php echo $tax->name; ?>checklist" class="list:<?php echo $tax->name?> categorychecklist form-no-clear"><?php
                    // show_none set? This doesn't do much but show a radio button
                    // TODO : actually have this checked when no term is selected
                    if ($tax->show_none) {
                        echo '<li><label class="selectit"><input value="" type="radio" name="tax_input['.$tax->name.'][]"'.(apply_filters('radio-taxonomy_none-checked', false, $metabox) ? ' checked="checked"' : '').'> ';
                        echo apply_filters('radio-taxonomy_none-text', __('None', 'radio-taxonomy'), $metabox);
                        echo '</label></li>';
                    }
                    $this->category_radio_list($post->ID, $tax->name);
                    ?>
                    </ul>
                </div>
            </div>
        </div>
		<?php
		do_action('radio-taxonomy_box_after');
	}
	
	function category_radio_list($post_id, $taxonomy) {
		wp_terms_checklist($post_id, array('taxonomy' => $taxonomy, 'checked_ontop' => false, 'walker' => new wpf_Walker_Category_RadioList));
	}
	
	function meta_boxes() {
		// Remove and create the new meta boxes
		if (!isset($this->taxonomies)) return;
		foreach ($this->taxonomies as $tax) {
			foreach ($tax->object_type as $post_type) {
				// Remove the old meta box
				remove_meta_box($tax->name.'div', $post_type, 'side');
				
				// Add the new meta box
				add_meta_box(
					$tax->name.'div', // id of the meta box, use the same as the old one we just removed.
					$tax->labels->singular_name, //title
					array(&$this,'meta_box'), // callback function that will echo the box content
					$post_type, // where to add the box: on "post", "page", or "link" page
					'side',
					'low',
					array('taxonomy' => $tax, 'post_type' => $post_type)
				);
			}
		}
	}
}
new wpf_radiotax;
endif;
?>